"""
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨，请访问：https://ceshiren.com/t/topic/15860'
"""
# 封装 driver, do_find, do_send_keys, wait_visible,
# pip install opencv-python
import allure
import cv2
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.webdriver import WebDriver
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

from app_practice.utils.log_util import logger


class Base:

    def __init__(self, base_driver=None):
        self.driver: WebDriver = base_driver

    def do_find(self, by, value=None):
        logger.info(f"查找元素{by, value}")
        """查找单个元素"""
        if value:
            ele = self.driver.find_element(by, value)
        else:
            # (By.ID,"")
            ele = self.driver.find_element(*by)

        imagepaht = self.draw_rectangle_in_screenshot(ele)
        allure.attach.file(imagepaht, name="截图", attachment_type=allure.attachment_type.PNG)

        return ele

    def do_finds(self, by, value=None):
        """查找多个元素"""
        # (By.ID,"")
        if value:
            return self.driver.find_elements(by, value)
        else:
            return self.driver.find_elements(*by)

    def do_send_keys(self, text, by, value=None):
        logger.info(f"输入内容{text}")
        """输入文本"""
        ele = self.do_find(by, value)
        ele.clear()
        ele.send_keys(text)

    def swipe_find(self, text, swipe_num=3):
        """滑动找某个文字"""
        # 找到元素，返回这个元素
        # 如果没有找到，就滑动
        # 滑动次数，最多为n次
        for i in range(swipe_num):
            try:
                logger.info(f"查找文字{text}")
                return self.driver.find_element(AppiumBy.XPATH, f"//*[@text='{text}']")
            except:
                logger.info(f"开始第{i + 1}次滑动")
                # 手机屏幕尺寸
                size = self.driver.get_window_size()
                # 'width', 'height'
                width = size.get('width')
                height = size.get('height')
                # x  宽的一半
                # y  屏幕的8/10 处 滑动到 3/10

                start_x = width / 2
                start_y = height * 0.8

                end_x = start_x
                end_y = height * 0.3

                duration = 2000
                # 滑动
                self.driver.swipe(start_x, start_y, end_x, end_y, duration)
            if i == swipe_num - 1:
                logger.info(f"找了{swipe_num}次，未找到")
                raise NoSuchElementException(f"找了{swipe_num}次，未找到")

    def get_toasttext(self):
        return self.driver.find_element(AppiumBy.XPATH, "//*[@class='android.widget.Toast']").text

    def screenshot(self, path):
        self.driver.save_screenshot(path)

    def draw_rectangle_in_screenshot(self, element, color_rgb=(255, 0, 0)):
        '''在图上上画矩形
        start_point: 起点的坐标，tuple 类型，例如：(100, 100)
        end_point: 终点的坐标，tuple 类型，例如：(200, 200)
        color_rgb: 画线对应的rgb颜色 例如：(0, 255, 0)
        '''
        start_x = element.location.get("x")
        start_y = element.location.get("y")
        end_x = element.size.get("width") + start_x
        end_y = element.size.get("height") + start_y
        start_point = (start_x, start_y)
        end_point = (end_x, end_y)
        img_path = "tmp.png"
        self.screenshot(img_path)

        # 读取图片
        image = cv2.imread(img_path)
        # 画矩形
        cv2.rectangle(image, start_point, end_point, color_rgb, 5)
        # 写到文件中
        cv2.imwrite(img_path, image)
        return img_path
